package today.rocky.boot.mongo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import today.rocky.boot.mongo.pojo.Book;
import today.rocky.boot.mongo.service.BookService;

import java.time.LocalDate;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @version 1.0
 * @vlog:
 * @description:
 * @author: Rocky
 * @createDate: 2020/6/9 20:51
 */
@Service
public class BookServiceImpl implements BookService {
	@Autowired
	private MongoTemplate mongoTemplate;

	@Override
	public void addBook(Book book) {
		mongoTemplate.save(book);
	}

	@Override
	public void updateBook(Book book) {
		Query query = new Query(Criteria.where("id").is(book.getId()));
		Update update = new Update().set("press", book.getPress())
									.set("name", book.getName())
				                    .set("publicationDate", LocalDate.now())
									.set("type",book.getType())
									.set("author",book.getAuthor())
									.set("edition",book.getEdition()+1);
		mongoTemplate.updateFirst(query, update, Book.class);

	}

	@Override
	public void deleteBook(Book book) {
		mongoTemplate.remove(book);
	}

	@Override
	public void deleteBookById(String id) {
		Book book = findById(id);
		mongoTemplate.remove(book);
	}

	@Override
	public List<Book> findByLike(String search){
		Pattern pattern = Pattern.compile("^.*" + search + ".*$" , Pattern.CASE_INSENSITIVE);
		System.out.println(pattern.toString());
		Query query = new Query(Criteria.where("name").regex(pattern));
		return mongoTemplate.findAllAndRemove(query, Book.class);
	}

	@Override
	public List<Book> findAll() {
		return mongoTemplate.findAll(Book.class);
	}

	@Override
	public Book findById(String id) {
		Query query = new Query(Criteria.where("id").is(id));
		//mongoTemplate.findById(id,Book.class);
		return mongoTemplate.findOne(query,Book.class);
	}

	@Override
	public Book findByName(String name) {
		Query query = new Query(Criteria.where("name").is(name));
		//mongoTemplate.findById(id,Book.class);
		return mongoTemplate.findOne(query,Book.class);
	}


}
